//
//  LCWHomeTableViewController.swift
//  MyWB
//
//  Created by 李成万 on 16/6/23.
//  Copyright © 2016年 李成万. All rights reserved.
//

import UIKit


class LCWHomeTableViewController: LCWVisitorTableViewController {

    let refresh = CZRefresh()
    
    var dataArray:[LCWStatus] = [LCWStatus]()
    override func viewDidLoad() {
        super.viewDidLoad()

        
        if isLogin == false{
            visitorView.startAnimation()
            return
        }
        loadHomeData(activityView.isAnimating())
        
        setupTableViewInfo()
    }

    
    func setupTableViewInfo(){
        
        tableView.registerClass(LCWShouYeCell.self, forCellReuseIdentifier:"cell")
        
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 200
        
        tableView.separatorStyle = .None
        
        tableView.tableFooterView = activityView
        
        
        tableView.addSubview(refresh)
        refresh.addTarget(self, action: "refreshAction", forControlEvents: UIControlEvents.ValueChanged)
    }

    //下拉刷新走这里
    func refreshAction(){
        loadHomeData(activityView.isAnimating())
        
    }
    private lazy var activityView : UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        view.color = ThemeColor
        
        return  view
    }()
}

extension LCWHomeTableViewController{
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       
        return self.dataArray.count
      
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! LCWShouYeCell
        
        cell.status = self.dataArray[indexPath.row]
        
//        cell.backgroundColor = randomColor()
//        cell.textLabel?.text = dataArray![indexPath.row].text
        return cell
    }
    
    //上拉时候走这里
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if dataArray.count == indexPath.row + 1 && !activityView.isAnimating() {
            activityView.startAnimating()
            
            loadHomeData(activityView.isAnimating())
            
        }
    }
}

extension LCWHomeTableViewController{
    
    func loadHomeData(pullUp:Bool){
        
    
        //        如果 下拉刷新 MaxId = 0 代表我要拿时间最新的微博
        //        如果 上拉加载更多 SinceI的 = 0 代表我要拿时间更早的微博
        var sinceId : Int64 = 0
        var maxId : Int64 = 0
        
        if pullUp{
            //上拉加载更多
            maxId = self.dataArray.last?.id ?? 0
            
//            if maxId > 0{
                maxId -= 1
                
//            }
        }else{
            sinceId = self.dataArray.first?.id ?? 0
        }
        
    LCWNetworkingTools.sharedTools.homeLoadData(sinceId, max_Id:maxId, success: { (response) -> () in
        self.endRefreshing()
//        print(response)
        guard let res = response?["statuses"] as? [[String:AnyObject]] else{
            return
        }
        
        var tempArr:[LCWStatus] = [LCWStatus]()
        
        for dic in res{
            let status = LCWStatus(dict: dic)
            tempArr.append(status)
        }
        // 上拉加载更多
        if pullUp{
            self.dataArray = self.dataArray + tempArr
            
        }else{
            // 下拉刷新
            self.dataArray = tempArr + self.dataArray
        }
//        print(self.dataArray.first?.id)
//        print(self.dataArray.last?.id)
//        print(maxId)
//        print(self.dataArray)
        self.tableView.reloadData()
        }) { (error) -> () in
            print(error)
        }
        
//    LCWNetworkingTools.sharedTools.homeLoadData({ (response) -> () in
////        print(response)
//        guard let res = response?["statuses"] as? [[String:AnyObject]] else{
//            return
//        }
//        
//        var tempArr:[LCWStatus] = [LCWStatus]()
//        
//        for dic in res{
//            let status = LCWStatus(dict: dic)
//            tempArr.append(status)
//        }
//        self.dataArray = tempArr
//        self.tableView.reloadData()
//        }) { (error) -> () in
//            print(error)
//        }
//
    }
//
    func endRefreshing(){
        self.activityView.stopAnimating()
        self.refresh.endRefreshing()
    }
}
